import Dep from "./observer/Dep";
export default  class Watcher {
    constructor(vm, expOrFn, cb, options) {
        this.vm = vm;
        this.cb = cb;
        this.getter = parsePath(expOrFn)
        this.value= this.get()
    }
    get () {
        window.target = this;
        const vm = this.vm;
        let value = this.getter.call(vm, vm)
        window.target = undefined;
        return value
    }
    update() {
        const oldValue = this.value;
        this.value = this.get()
        this.cb.call(this.vm, this.value, oldValue)
    }
}

const bailRe = /[^\w.$]/
export function parsePath(path) {
    if(bailRe.test(path)) {
        return
    }
    const segments = path.split('.')
    return function (obj) {
        for(let i = 0; i< segments.length; i++) {
            if(!obj) return
            obj = obj[segments[i]]
        }
        return obj
    }
}